package com.fhao.forum.controller;

import com.fhao.forum.common.AppResult;
import com.fhao.forum.common.ResultCode;
import com.fhao.forum.config.AppConfig;
import com.fhao.forum.model.Article;
import com.fhao.forum.model.ArticleReply;
import com.fhao.forum.model.User;
import com.fhao.forum.services.IArticleReplyService;
import com.fhao.forum.services.IArticleService;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@ApiResponses
@RequestMapping("/reply")
public class ArticleReplyController {

    @Resource
    private IArticleReplyService articleReplyService;

    @Resource
    private IArticleService articleService;

    @ApiResponse(description = "回复帖子")
    @PostMapping("/create")
    public AppResult create(HttpServletRequest request,
                            @RequestParam("articleId") @NonNull Long articleId,
                            @RequestParam("content")   @NonNull String content) {
        //判断当前登录用户是否禁言
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //判断帖子是否存在/删除,是否封贴
        Article article = articleService.selectById(articleId);
        if(article == null || article.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        if(article.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }
        //创建ArticleReply对象
        ArticleReply updateArticleReply = new ArticleReply();
        updateArticleReply.setArticleId(articleId);
        updateArticleReply.setContent(content);
        updateArticleReply.setPostUserId(user.getId());
        //调用service层,写入数据库
        articleReplyService.create(updateArticleReply);
        return AppResult.success();
    }

    @ApiResponse(description = "查询回复列表")
    @GetMapping("/getReplies")
    public AppResult<List<ArticleReply>> getRepliesByArticleId(@RequestParam("articleId") @NonNull Long articleId) {
        if(articleId == null || articleId <= 0) {
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        List<ArticleReply> articleReplies = articleReplyService.selectByArticleId(articleId);
        if(articleReplies == null) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_RELY_NOT_EXISTS);
        }
        return AppResult.success(articleReplies);
    }
}

















